<template>
  <div class="aprd-container">
    <!-- 搜索区域 -->
    <div class="aprd-search-container">
      <el-form :inline="true" :model="searchParams" class="aprd-search-form">
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="searchParams.startTime"
            type="datetime"
            placeholder="选择日期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            size="small"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="searchParams.endTime"
            type="datetime"
            placeholder="选择日期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            size="small"
          />
        </el-form-item>
        <el-form-item label="母卷号">
          <el-input v-model="searchParams.parentCoilNo" placeholder="请输入母卷号" size="small" clearable></el-input>
        </el-form-item>
        <el-form-item label="出口卷号">
          <el-input v-model="searchParams.exitCoilNo" placeholder="请输入出口卷号" size="small" clearable></el-input>
        </el-form-item>
        <el-form-item label="宽度分档">
          <el-select v-model="searchParams.widthBin" placeholder="请选择" size="small" clearable>
            <el-option label="档位1" value="1"></el-option>
            <el-option label="档位2" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入口厚度分档">
          <el-select v-model="searchParams.entryThicknessBin" placeholder="请选择" size="small" clearable>
             <el-option label="档位A" value="A"></el-option>
             <el-option label="档位B" value="B"></el-option>
          </el-select>
        </el-form-item>
         <el-form-item label="出口厚度分档">
           <el-select v-model="searchParams.exitThicknessBin" placeholder="请选择" size="small" clearable>
             <el-option label="厚档1" value="T1"></el-option>
             <el-option label="厚档2" value="T2"></el-option>
           </el-select>
         </el-form-item>
         <el-form-item label="钢种分档">
           <el-select v-model="searchParams.steelGradeBin" placeholder="请选择" size="small" clearable>
             <el-option label="钢种X" value="X"></el-option>
             <el-option label="钢种Y" value="Y"></el-option>
           </el-select>
         </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" size="small">查询</el-button>
          <el-button @click="handleReset" size="small">重置</el-button>
          <el-button type="success" @click="handleExport" size="small">导出</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="aprd-table-container">
      <el-table :data="tableData" border style="width: 100%" :header-cell-style="headerStyle" height="100%">
        <el-table-column prop="seqNo" label="序号" width="60" fixed="left" align="center"/>
        <el-table-column prop="exitCoilNo" label="出口卷号" width="150" fixed="left" align="center"/>

        <!-- 带钢位置最大值 -->
        <el-table-column label="带钢位置最大值" align="center">
          <el-table-column v-for="i in 10" :key="'max_strip_'+i" :prop="'max_strip'+i" :label="'Strip'+i" width="80" align="center">
             <template #default="scope">
               {{ scope.row['max_strip'+i] != null ? scope.row['max_strip'+i].toFixed(2) : '-' }}
             </template>
          </el-table-column>
        </el-table-column>

        <!-- 带钢位置均值 -->
        <el-table-column label="带钢位置均值" align="center">
           <el-table-column v-for="i in 10" :key="'avg_strip_'+i" :prop="'avg_strip'+i" :label="'Strip'+i" width="80" align="center">
             <template #default="scope">
               {{ scope.row['avg_strip'+i] != null ? scope.row['avg_strip'+i].toFixed(2) : '-' }}
             </template>
           </el-table-column>
        </el-table-column>

        <el-table-column label="详情" width="80" fixed="right" align="center">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="showDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="aprd-pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalItems"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          size="small"
        />
      </div>
    </div>

     <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="跑偏详细信息"
      width="90%"
      top="5vh"
      class="aprd-detail-dialog"
      destroy-on-close
      @closed="handleDialogClose"
    >
      <div class="aprd-detail-container">
        <!-- 顶部信息 -->
        <div class="aprd-detail-info">
          <el-descriptions :column="9" border size="small">
            <el-descriptions-item label="母卷号">{{ detailData.parentCoilNo }}</el-descriptions-item>
            <el-descriptions-item label="出口卷号">{{ detailData.exitCoilNo }}</el-descriptions-item>
            <el-descriptions-item label="钢种">{{ detailData.steelGrade }}</el-descriptions-item>
            <el-descriptions-item label="出口宽度[mm]">{{ detailData.exitWidth }}</el-descriptions-item>
            <el-descriptions-item label="出口厚度[mm]">{{ detailData.exitThickness }}</el-descriptions-item>
            <el-descriptions-item label="长度[m]">{{ detailData.length }}</el-descriptions-item>
            <el-descriptions-item label="预测跑偏概率[%]">{{ detailData.deviationProb }}</el-descriptions-item>
            <el-descriptions-item label="纠偏次数">{{ detailData.correctionCount }}</el-descriptions-item>
            <el-descriptions-item label="带钢跑偏">{{ detailData.stripDeviation }}</el-descriptions-item>
            <el-descriptions-item label="时间">{{ detailData.time }}</el-descriptions-item>
            <el-descriptions-item label="班次">{{ detailData.shift }}</el-descriptions-item>
            <el-descriptions-item label="班组">{{ detailData.crew }}</el-descriptions-item>
            <el-descriptions-item label="钢种分档">{{ detailData.steelGradeBin }}</el-descriptions-item>
            <el-descriptions-item label="宽度分档">{{ detailData.widthBin }}</el-descriptions-item>
            <el-descriptions-item label="入口厚度分档">{{ detailData.entryThicknessBin }}</el-descriptions-item>
            <el-descriptions-item label="出口厚度分档">{{ detailData.exitThicknessBin }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 图表区域 -->
        <div class="aprd-detail-charts-area">
          <!-- 左侧 CPC 图表 -->
          <div class="aprd-cpc-charts">
            <div v-for="i in 7" :key="'cpc'+i" class="aprd-chart-item aprd-cpc-chart-item">
              <div class="aprd-chart-title">CPC {{ i }}</div>
              <div class="aprd-chart" :ref="el => { if (el) cpcChartRefs[i-1] = el as HTMLElement }"></div>
            </div>
          </div>

          <!-- 右侧 分析 + 图表 -->
          <div class="aprd-analysis-charts">
            <!-- 跑偏原因智能分析 -->
            <div class="aprd-analysis-section aprd-chart-item">
              <div class="aprd-chart-title">跑偏原因智能分析</div>
              <div class="aprd-analysis-content">
                <div class="analysis-item">
                  <span>是否特殊钢种:</span>
                  <el-tag :type="detailData.isSpecialSteel ? 'warning' : 'success'" size="small">{{ detailData.isSpecialSteel ? '是' : '否' }}</el-tag>
                </div>
                <div class="analysis-item">品规历史跑偏风险: {{ detailData.historyRisk }}%</div>
                <div class="analysis-item">热轧来料情况: {{ detailData.hotRollCondition }}</div>
                <div class="analysis-item">凸度命中率: {{ detailData.convexityRate }}%</div>
                <div class="analysis-item">楔形命中率: {{ detailData.wedgeRate }}%</div>
              </div>
            </div>

            <!-- 凸度/楔形图表 -->
            <div class="aprd-chart-item">
              <div class="aprd-chart-title">凸度曲线-C40 / 楔形曲线-W40 (μm)</div>
              <div class="aprd-chart" ref="convexityWedgeChartRef"></div>
            </div>

            <!-- 生产过程追溯图表 -->
            <div class="aprd-chart-item">
              <div class="aprd-chart-title">生产过程追溯</div>
              <div class="aprd-chart" ref="processTraceChartRef"></div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false" size="small">关闭</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts/core'
import {
  LineChart,
} from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  MarkLineComponent,
  ToolboxComponent, // Added for potential chart tools
  DataZoomComponent // Added for potential zooming
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import type { EChartsOption } from 'echarts'

// Register ECharts components
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  MarkLineComponent,
  ToolboxComponent,
  DataZoomComponent,
  LineChart,
  CanvasRenderer
])

// 搜索参数
const searchParams = reactive({
  startTime: '2025-03-30 14:31:47',
  endTime: '2025-03-31 14:31:47',
  parentCoilNo: '',
  exitCoilNo: '',
  widthBin: '',
  entryThicknessBin: '',
  exitThicknessBin: '',
  steelGradeBin: '',
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(30)
const totalItems = ref(278)

// 表头样式
const headerStyle = {
  background: '#eef1f6',
  color: '#606266'
}

// 表格数据 (模拟)
const tableData = reactive(
  Array.from({ length: 19 }, (_, i) => ({
    seqNo: i + 1,
    exitCoilNo: `L125023688${String(i).padStart(2, '0')}`,
    parentCoilNo: `22520484${String(i+10).padStart(2, '0')}`, // Added parent coil no
    steelGrade: i % 3 === 0 ? 'SPCD' : 'SPCC',
    exitWidth: 1250 + i,
    exitThickness: 0.98 + i * 0.01,
    length: 1664 + i * 10,
    deviationProb: i % 5,
    correctionCount: i % 10,
    stripDeviation: i % 2,
    time: `2025-03-31 14:16:${String(16+i).padStart(2, '0')}`,
    shift: (i % 3) + 1,
    crew: ['A', 'B', 'C'][i%3],
    steelGradeBin: (i % 4) + 1,
    widthBin: (i % 5) + 5,
    entryThicknessBin: (i % 2) + 1,
    exitThicknessBin: (i % 3) + 10,
    max_strip1: -8.6 + Math.random() * 5,
    max_strip2: 11.03 + Math.random() * 5,
    max_strip3: -9.38 + Math.random() * 5,
    max_strip4: -5.22 + Math.random() * 5,
    max_strip5: 4.65 + Math.random() * 5,
    max_strip6: -7.95 + Math.random() * 5,
    max_strip7: 2.6 + Math.random() * 5,
    max_strip8: 2.17 + Math.random() * 5,
    max_strip9: -3.6 + Math.random() * 5,
    max_strip10: 1.7 + Math.random() * 5,
    avg_strip1: 0.28 + Math.random(),
    avg_strip2: 0.51 + Math.random(),
    avg_strip3: 0.76 + Math.random(),
    avg_strip4: 0.63 + Math.random(),
    avg_strip5: 2.38 + Math.random(),
    avg_strip6: -0.34 + Math.random(),
    avg_strip7: 0.81 + Math.random(),
    avg_strip8: 0.18 + Math.random(),
    avg_strip9: -0.11 + Math.random(),
    avg_strip10: 0.03 + Math.random(),
  }))
)

// 详情弹窗
const detailDialogVisible = ref(false)
const detailData = reactive({ // Structure for detail data
  parentCoilNo: '',
  exitCoilNo: '',
  steelGrade: '',
  exitWidth: null,
  exitThickness: null,
  length: null,
  deviationProb: null,
  correctionCount: null,
  stripDeviation: null,
  time: '',
  shift: null,
  crew: '',
  steelGradeBin: null,
  widthBin: null,
  entryThicknessBin: null,
  exitThicknessBin: null,
  isSpecialSteel: false,
  historyRisk: 0,
  hotRollCondition: '良好',
  convexityRate: 0,
  wedgeRate: 0,
  // Add chart data arrays here if needed, or generate in init functions
  cpcData: [] as { x: number[]; ds: number[]; os: number[] }[],
  convexityWedgeData: { x: [] as number[], c40: [] as number[], w40: [] as number[], upper: [] as number[], lower: [] as number[] },
  processTraceData: { x: [] as number[], tensionDiff1: [] as number[], tensionDiff2: [] as number[], speed: [] as number[] }
})

// Chart Refs
const cpcChartRefs = ref<HTMLElement[]>([]);
const convexityWedgeChartRef = ref<HTMLElement | null>(null);
const processTraceChartRef = ref<HTMLElement | null>(null);

// Chart Instances
let cpcChartInstances: (echarts.ECharts | null)[] = [];
let convexityWedgeChartInstance: echarts.ECharts | null = null;
let processTraceChartInstance: echarts.ECharts | null = null;

// --- 事件处理函数 ---
const handleSearch = () => { ElMessage.success('执行查询'); console.log('查询参数:', searchParams) }
const handleReset = () => { /* ... reset logic ... */ ElMessage.info('重置搜索条件'); }
const handleExport = () => { ElMessage.success('执行导出') }
const handleSizeChange = (val: number) => { pageSize.value = val; currentPage.value = 1; console.log(`每页 ${val} 条`) }
const handleCurrentChange = (val: number) => { currentPage.value = val; console.log(`当前页: ${val}`) }

const showDetail = (row: any) => {
  // Assign basic info
  Object.keys(detailData).forEach(key => {
    if (row[key] !== undefined) {
      (detailData as any)[key] = row[key];
    }
  });
  // Add specific mock data for analysis section
  detailData.isSpecialSteel = row.seqNo % 4 === 0;
  detailData.historyRisk = row.seqNo % 10;
  detailData.hotRollCondition = ['良好', '一般', '需关注'][row.seqNo % 3];
  detailData.convexityRate = Math.floor(Math.random() * 101);
  detailData.wedgeRate = Math.floor(Math.random() * 101);

  // TODO: Fetch real detailed data including chart data if necessary
  // For now, generate mock chart data
  generateMockChartData();

  detailDialogVisible.value = true;

  // Initialize charts after dialog is rendered
  nextTick(() => {
    initDetailCharts();
  });
}

// --- Chart Initialization ---

// Mock Data Generation (replace with actual data fetching)
const generateMockChartData = () => {
  detailData.cpcData = Array.from({ length: 7 }, () => ({
    x: Array.from({ length: 50 }, (_, i) => i + 1),
    ds: Array.from({ length: 50 }, () => Math.random() * 60 + 20),
    os: Array.from({ length: 50 }, () => Math.random() * 60 + 20)
  }));

  const len = 25;
  detailData.convexityWedgeData.x = Array.from({ length: len }, (_, i) => i * 20 + 1); // X-axis like image
  detailData.convexityWedgeData.c40 = Array.from({ length: len }, () => Math.random() * 20 + 30);
  detailData.convexityWedgeData.w40 = Array.from({ length: len }, () => Math.random() * 20 - 30);
  detailData.convexityWedgeData.upper = Array(len).fill(50);
  detailData.convexityWedgeData.lower = Array(len).fill(-40);

  detailData.processTraceData.x = Array.from({ length: 50 }, (_, i) => i+1);
  detailData.processTraceData.tensionDiff1 = Array.from({ length: 50 }, () => Math.random() * 10 + 5); // Example scale
  detailData.processTraceData.tensionDiff2 = Array.from({ length: 50 }, () => Math.random() * 10 + 15);
  detailData.processTraceData.speed = Array.from({ length: 50 }, () => Math.random() * 400 + 600); // Example scale
};

const initDetailCharts = () => {
  disposeCharts(); // Dispose previous instances first
  cpcChartInstances = [];

  // Init CPC Charts
  cpcChartRefs.value.forEach((ref, index) => {
    if (ref && detailData.cpcData[index]) {
      const chart = echarts.init(ref);
      const cpcOption: EChartsOption = {
        tooltip: { trigger: 'axis' },
        grid: { left: '15%', right: '5%', top: '15%', bottom: '15%' }, // Adjusted grid
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: detailData.cpcData[index].x,
          axisLabel: { fontSize: 10 }
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 100,
          axisLabel: { fontSize: 10 }
        },
        series: [
          {
            name: 'DS',
            type: 'line',
            smooth: true,
            symbol: 'none',
            data: detailData.cpcData[index].ds,
            lineStyle: { color: '#5470C6' } // Example color
          },
          {
            name: 'OS',
            type: 'line',
            smooth: true,
            symbol: 'none',
            data: detailData.cpcData[index].os,
            lineStyle: { color: '#91CC75' } // Example color
          }
        ]
      };
      chart.setOption(cpcOption);
      cpcChartInstances.push(chart);
    }
  });

  // Init Convexity/Wedge Chart
  if (convexityWedgeChartRef.value) {
    convexityWedgeChartInstance = echarts.init(convexityWedgeChartRef.value);
    const cwOption: EChartsOption = {
      tooltip: { trigger: 'axis' },
      legend: {
        data: ['凸度曲线-C40', '楔形曲线-W40'],
        bottom: 5,
        textStyle: { fontSize: 10 }
      },
      grid: { left: '10%', right: '8%', top: '10%', bottom: '20%' },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: detailData.convexityWedgeData.x,
        name: '(m)', // X-axis name
        nameLocation: 'end',
        axisLabel: { fontSize: 10 }
      },
      yAxis: {
        type: 'value',
        name: 'μm', // Y-axis name
        axisLabel: { fontSize: 10 }
        // Consider min/max based on data or image
      },
      series: [
        {
          name: '凸度曲线-C40',
          type: 'line',
          smooth: true,
          symbol: 'none',
          data: detailData.convexityWedgeData.c40,
          lineStyle: { color: '#5470C6' },
          markLine: {
              symbol: ['none', 'none'],
              label: { show: true, position: 'end', formatter: '上限' },
              data: [{ yAxis: 50 }], // Example upper limit
              lineStyle: { type: 'dashed', color: '#F56C6C' }
          }
        },
        {
          name: '楔形曲线-W40',
          type: 'line',
          smooth: true,
          symbol: 'none',
          data: detailData.convexityWedgeData.w40,
          lineStyle: { color: '#EE6666' },
           markLine: {
              symbol: ['none', 'none'],
              label: { show: true, position: 'end', formatter: '下限' },
              data: [{ yAxis: -40 }], // Example lower limit
              lineStyle: { type: 'dashed', color: '#F56C6C' }
          }
        }
      ]
    };
    convexityWedgeChartInstance.setOption(cwOption);
  }

  // Init Process Trace Chart
  if (processTraceChartRef.value) {
    processTraceChartInstance = echarts.init(processTraceChartRef.value);
    const ptOption: EChartsOption = {
      tooltip: { trigger: 'axis' },
      legend: {
        data: ['5机张力差', '5机张力差2', '5机出口速度'], // Names adjusted
        bottom: 5,
        textStyle: { fontSize: 10 }
      },
      grid: { left: '10%', right: '15%', top: '10%', bottom: '20%' }, // Adjust right for dual axis
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: detailData.processTraceData.x,
        axisLabel: { fontSize: 10 }
      },
      yAxis: [
        {
          type: 'value',
          name: 'KN', // Y-axis 1 name
          position: 'left',
          axisLabel: { fontSize: 10 }
          // Consider scale based on tension data
        },
        {
          type: 'value',
          name: 'm/min', // Y-axis 2 name
          position: 'right',
          axisLabel: { fontSize: 10 }
          // Consider scale based on speed data
        }
      ],
      series: [
        {
          name: '5机张力差',
          type: 'line',
          yAxisIndex: 0,
          smooth: true,
          symbol: 'none',
          data: detailData.processTraceData.tensionDiff1,
          lineStyle: { color: '#5470C6' }
        },
         {
          name: '5机张力差2', // Added second tension series
          type: 'line',
          yAxisIndex: 0,
          smooth: true,
          symbol: 'none',
          data: detailData.processTraceData.tensionDiff2,
          lineStyle: { color: '#91CC75' }
        },
        {
          name: '5机出口速度',
          type: 'line',
          yAxisIndex: 1,
          smooth: true,
          symbol: 'none',
          data: detailData.processTraceData.speed,
          lineStyle: { color: '#FAC858' }
        }
      ]
    };
    processTraceChartInstance.setOption(ptOption);
  }
}

// --- Chart Cleanup & Resize ---
const disposeCharts = () => {
  cpcChartInstances.forEach(chart => chart?.dispose());
  convexityWedgeChartInstance?.dispose();
  processTraceChartInstance?.dispose();
  cpcChartInstances = [];
  convexityWedgeChartInstance = null;
  processTraceChartInstance = null;
}

const handleDialogClose = () => {
  disposeCharts();
}

const handleResize = () => {
  cpcChartInstances.forEach(chart => chart?.resize());
  convexityWedgeChartInstance?.resize();
  processTraceChartInstance?.resize();
}

onMounted(() => {
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  disposeCharts(); // Ensure cleanup on component unmount
});

</script>

<style scoped>
/* ... (之前的样式保持不变) ... */
.aprd-container {
  padding: 15px;
  background-image: linear-gradient(to top, white, #2c69e8) !important;
  height: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.aprd-search-container {
  margin-bottom: 15px;
  padding: 10px 15px;
  background-color: rgba(245, 247, 250, 0.8);
  border-radius: 4px;
  flex-shrink: 0;
}

.aprd-search-form .el-form-item {
  margin-bottom: 8px;
  margin-right: 10px;
}

:deep(.aprd-search-form .el-input--small .el-input__wrapper),
:deep(.aprd-search-form .el-select--small .el-select__wrapper),
:deep(.aprd-search-form .el-date-editor--small.el-input__wrapper) {
    height: 28px;
    line-height: 28px;
}
:deep(.aprd-search-form .el-input--small .el-input__inner),
:deep(.aprd-search-form .el-select--small .el-select__input-wrapper input),
:deep(.aprd-search-form .el-date-editor--small .el-range-input),
:deep(.aprd-search-form .el-date-editor--small .el-range-separator) {
    height: 26px !important;
    line-height: 26px !important;
    font-size: 12px !important;
}

:deep(.aprd-search-form .el-select--small) {
    width: 150px;
}

:deep(.aprd-search-form .el-form-item__label) {
    font-size: 12px;
    line-height: 28px;
    color: #606266;
    padding-right: 8px;
}

.aprd-table-container {
  flex-grow: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
  /* Added border and background for context */
  border: 1px solid #dcdfe6;
  background-color: #fff;
  border-radius: 4px;
}

:deep(.el-table) {
  font-size: 12px;
}
:deep(.el-table th.el-table__cell) {
  padding: 6px 0;
  background-color: #f5f7fa !important; /* Lighter header */
  color: #606266 !important;
  font-weight: 500;
}
:deep(.el-table td.el-table__cell) {
  padding: 4px 0;
}
:deep(.el-table .el-table__cell) {
  text-align: center;
}
:deep(.el-table__body tr td.el-table-fixed-column--left),
:deep(.el-table__body tr td.el-table-fixed-column--right) {
    /* Ensure fixed columns have background consistent with row */
    background-color: inherit !important;
}
:deep(.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell) {
   background-color: #ecf5ff !important;
}
:deep(.el-table__body tr.current-row > td.el-table__cell) {
   background-color: #d9ecff !important;
}

.aprd-pagination {
  margin-top: 15px;
  padding: 5px 10px;
  background-color: #fff; /* Match table container background */
  border-top: 1px solid #dcdfe6;
  border-radius: 0 0 4px 4px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

/* --- Detail Dialog Styles --- */
:deep(.aprd-detail-dialog .el-dialog__header) {
  background-color: #f5f7fa; /* Light header background */
  padding: 10px 20px;
  margin-right: 0;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.aprd-detail-dialog .el-dialog__title) {
  color: #303133; /* Darker title color */
  font-size: 16px;
  font-weight: 600;
}

:deep(.aprd-detail-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: #909399;
}
:deep(.aprd-detail-dialog .el-dialog__headerbtn .el-dialog__close:hover) {
  color: #409EFF;
}

:deep(.aprd-detail-dialog .el-dialog__body) {
  padding: 0; /* Remove default body padding */
}

.aprd-detail-container {
  padding: 15px;
  max-height: calc(90vh - 50px - 60px); /* Viewport height - top offset - header - footer */
  overflow-y: auto;
  background-color: #fff; /* Ensure white background inside */
}

.aprd-detail-info {
  margin-bottom: 15px;
}

:deep(.aprd-detail-info .el-descriptions__label) {
  background-color: #f5f7fa;
  font-weight: normal;
  color: #606266;
}
:deep(.aprd-detail-info .el-descriptions__content) {
  color: #303133;
}

.aprd-detail-charts-area {
  display: flex;
  gap: 15px;
  min-height: 450px; /* Ensure minimum height for charts */
}

.aprd-cpc-charts {
  flex: 1; /* Takes remaining space */
  display: flex;
  flex-direction: column;
  gap: 5px; /* Smaller gap between cpc charts */
}

.aprd-analysis-charts {
  flex: 0 0 45%; /* Fixed width for the right panel */
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.aprd-chart-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.aprd-chart-title {
  padding: 8px 12px;
  font-size: 13px;
  font-weight: 600;
  color: #303133;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  flex-shrink: 0;
}

.aprd-chart {
  height: 100%; /* Default height for right charts */
  min-height: 150px; /* Minimum height for charts */
  flex-grow: 1;
}

.aprd-cpc-chart-item .aprd-chart {
   height: 80px; /* Specific smaller height for CPC charts */
   min-height: 80px;
}

.aprd-analysis-section {
  min-height: 150px; /* Ensure analysis section has some height */
}

.aprd-analysis-content {
  padding: 10px 15px;
  font-size: 12px;
  color: #606266;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.aprd-analysis-content .analysis-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* Scrollbar styling for detail container */
.aprd-detail-container::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}
.aprd-detail-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}
.aprd-detail-container::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 3px;
}
.aprd-detail-container::-webkit-scrollbar-thumb:hover {
  background-color: #a8abb2;
}

/* Footer alignment */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

</style>
